package data;

import org.hibernate.Hibernate;
import org.hibernate.Session;

import viajaGratis.Oferta;

public class OfertaDAO {

	private Oferta checkOferta(Integer id){
		Session session=HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		Oferta peticion=(Oferta)session.createQuery("from Oferta as m where m.idOferta=?").setInteger(0,id).uniqueResult();
		return peticion;
	}
	
	public Oferta selectById(Integer id){
		Session session=HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		Oferta peticion=(Oferta)session.createQuery("from Oferta as m where m.idOferta=?").setInteger(0,id).uniqueResult();
		if(peticion!=null){
			Hibernate.initialize(peticion);
			Hibernate.initialize(peticion.getVivienda());
			Hibernate.initialize(peticion.getSolicitudes());
		}
		return peticion;
	}
	
	public void insert(Oferta u){
		if(checkOferta(u.getIdOferta())==null){
			Session session=HibernateUtil.getSessionFactory().getCurrentSession();
			session.beginTransaction();
			session.save(u);
			session.flush();
			session.getTransaction().commit();
		}
	}
	
	public void delete(Oferta u){
		Session session=HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		Object oferta=session.load(Oferta.class,u.getIdOferta());
		session.delete(oferta);
		session.getTransaction().commit();
	}
	
	public void update(Oferta u){
		if(checkOferta(u.getIdOferta())!=null){
			Session session=HibernateUtil.getSessionFactory().getCurrentSession();
			session.beginTransaction();
			session.update(u);
			session.flush();
			session.getTransaction().commit();
		}
	}
}
